/* eslint-disable react/no-array-index-key */
/**
 * 需求简历，详情页
 */
import React from 'react';
import { history } from 'umi'
import { PageContainer } from '@/molecules';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Tabs, Row, Spin, Icon } from 'antd';
import helper from '@/utils/auth/helper';
import { connect } from 'umi';
import { eventTrack } from '@/utils/track';
import { queryTalentDuties } from '@/pages/Recruitment/service';
import { useRenderDuty } from '@/pages/Recruitment/hooks';
import { sameTabProps } from '@/utils/tab';

import styles from './Detail.less';
import { TalentInfoHead, Operates } from '../components';
import {
    BackgroundRecOperate,
    ThumbCommentGroup,
    TalentStatusStep,
    ResumeDetail,
    InterviewCard,
    InterviewInviteOperate,
    WeedOutOperate,
    TransferOperate,
    RecommendOperate,
    // InterviewEditOperate,
    TalentsBlackListOperate
} from '../containers';
import HireDetail from '../Hire/HireDetail/HireDetail';
import { getResumesDetail, getCandidateDetail, queryInterviewDetailList, setRead } from '../service';
import TalentDetailContext from '../TalentDetailContext';

const { checkCode } = helper;

const Detail = ({ location, user }) => {
    const { query } = location;
    const { currentUser = {} } = user;
    const [stepShow, setStepShow] = React.useState(true);
    const {
        id: originResumeId,
        candidateId: queryCandidateId,
        // contactId: queryContactId,
        activeKey,
        employId: queryEmployId
    } = query;

    const hireDetailRef = React.useRef();
    // const [recruitStatus, setRecruitStatus] = React.useState('');
    const id = query.currResumeId || originResumeId;

    // 设置简历已读
    React.useEffect(() => {
        if (id) {
            setRead(id);
        }
    }, []);

    // 人才信息
    const { data = {}, loading, run } = useRequest(() => getResumesDetail(id), {
        refreshDeps: [id]
    });
    const employId = data.data?.employId ?? queryEmployId;

    // 人才库信息
    const { data: talentDutyInfo, loading: talentDutyInfoLoading, run: runTalentDutyInfo } = useRequest(
        () => queryTalentDuties(data.data?.talentCode),
        {
            ...defaultFormatResult,
            ready: !!data.data?.talentCode
        }
    );

    // 刷新
    const onRefresh = React.useCallback(() => {
        run();
    }, [run]);
    // 岗位权限
    const auth = React.useMemo(() => {
        const hasRecruitAuth = data?.hasRecruitAuth ?? true; // 当前用户是否有查看 面试、录用等阶段的权限
        return {
            RESUME: checkCode('office:recruitment:course:resume'), // 简历
            INTERVIEW: checkCode('office:recruitment:course:interview') && hasRecruitAuth, // 面试
            HIRE: checkCode('office:recruitment:course:hire') && hasRecruitAuth // 录用
        };
    }, [data?.hasRecruitAuth]);
    const tabActiveKey = React.useMemo(() => {
        if (!activeKey) {
            return Object.keys(auth).find(key => auth[key]);
        }
        return activeKey;
    }, [activeKey]);
    const handleTabChange = key => {
        history.push({
            query: {
                ...query,
                activeKey: key
            },
            ...sameTabProps
        });
    };
    const [refreshComponents, setRefreshComponents] = React.useState([]);
    // 设置哪些模块需刷新
    const pushRefreshComponents = React.useCallback(comps => {
        setRefreshComponents(arr => arr.concat(comps));
    }, []);

    // 移除徐刷新的
    const removeRefreshedComponent = React.useCallback(comp => {
        setRefreshComponents(arr => arr.filter(item => item !== comp));
    }, []);

    // 判断模块是否需要刷新，用于推荐、拉黑等状态改变
    const getRefreshByKey = React.useCallback(key => refreshComponents.findIndex(com => com === key) !== -1, [
        refreshComponents
    ]);

    const talentInfo = React.useMemo(() => {
        const d = data?.data || {};
        return { ...d, id, hasBlackList: talentDutyInfo?.hasBlackList };
    }, [data, id, talentDutyInfo]);

    // 两个来源
    const candidateId = React.useMemo(() => talentInfo.candidateId || queryCandidateId, [queryCandidateId, talentInfo]);

    // 当前登录人是否为招聘负责人
    const principalFlag = React.useMemo(() => talentInfo?.principalEmployeeCode === currentUser?.employeeCode, [
        talentInfo?.principalEmployeeCode,
        currentUser?.employeeCode
    ]);
    // 当前登录人是否为招聘发起人
    const launcherFlag = React.useMemo(() => talentInfo?.launchEmployeeCode === currentUser?.employeeCode, [
        talentInfo?.launchEmployeeCode,
        currentUser?.employeeCode
    ]);
    // 验证是否为面试官
    const isInterviewer = React.useCallback(
        (employeeArr = []) => employeeArr.some(item => item?.employeeCode === currentUser?.employeeCode),
        [currentUser?.employeeCode]
    );

    // 候选人详情
    const { data: candidateDetail = {}, loading: candidateDetailDetailLoading, run: runCandidateDetail } = useRequest(
        () => {
            if (candidateId) return getCandidateDetail(candidateId);
            return Promise.resolve({ code: 10000, data: {} });
        },
        {
            refreshDeps: [candidateId],
            ...defaultFormatResult
        }
    );
    // 面试详情列表
    const {
        data: interviewDetailList = [],
        loading: interviewDetailListLoading,
        run: runInterviewDetailList
    } = useRequest(
        () => {
            if (candidateId) return queryInterviewDetailList(candidateId);
            return Promise.resolve({ code: 10000, data: [] });
        },
        {
            refreshDeps: [candidateId],
            ...defaultFormatResult
        }
    );
    // 刷新数据
    React.useEffect(() => {
        if (getRefreshByKey('TalentDutyInfo')) {
            runTalentDutyInfo();
            removeRefreshedComponent('TalentDutyInfo');
        }
        if (getRefreshByKey('CandidateDetail')) {
            runCandidateDetail();
            removeRefreshedComponent('CandidateDetail');
        }
        if (getRefreshByKey('InterviewDetailList')) {
            runInterviewDetailList();
            removeRefreshedComponent('InterviewDetailList');
        }
        if (getRefreshByKey('HireDetail')) {
            if (hireDetailRef.current) {
                hireDetailRef.current.runHireDetail();
                removeRefreshedComponent('HireDetail');
            }
        }
    }, [refreshComponents]);

    // 面试页签
    const interviewTab = React.useMemo(() => {
        const { resumeStep } = talentInfo;
        if (resumeStep === 1 || !candidateId || !interviewDetailList.length) {
            return '';
        }
        return (
            <Tabs.TabPane tab={`面试(${interviewDetailList.length})`} key="INTERVIEW">
                {interviewDetailList.map((item, index) => (
                    // id：锚点。操作步骤那边需要跳转至对应的面试记录
                    <div id={`INTERVIEW_DETAIL-${item?.contactRecordDetailVO?.id}`} key={index}>
                        <InterviewCard
                            data={item}
                            candidateId={candidateId}
                            resumeId={id}
                            principalFlag={principalFlag}
                            launcherFlag={launcherFlag}
                            interviewerFlag={isInterviewer(item?.arrangeDetailVO?.interviewEmployees)}
                        />
                        {index !== interviewDetailList.length - 1 && <div style={{ marginBottom: 20 }}></div>}
                    </div>
                ))}
            </Tabs.TabPane>
        );
    }, [interviewDetailList, candidateId, talentInfo.resumeStep, id]);

    // 录用页签
    const hireTab = React.useMemo(() => {
        const { resumeStep } = talentInfo;
        if (resumeStep < 4) {
            return null;
        }
        return (
            <Tabs.TabPane tab="录用" key="HIRE">
                <HireDetail
                    employId={talentInfo?.employId}
                    candidateId={talentInfo?.candidateId}
                    hireDetailRef={hireDetailRef}
                    // onHireData={hireData => {
                    //     setRecruitStatus(hireData.recruitStatus);
                    // }}
                />
            </Tabs.TabPane>
        );
    }, [talentInfo.resumeStep, talentInfo.employId]);

    const renderBtn = () => {
        const fetchOperates = () => {
            // eslint-disable-next-line max-len
            const { resumeStep, praiseEmployeeNameList, trampleEmployeeNameList, evaluateType, recruitList = [] } =
                talentInfo || {};
            const { candidateStatus } = candidateDetail || {};
            const { interviewStatus } = interviewDetailList?.[0]?.arrangeDetailVO || {};
            // // 是否是面试阶段中其中一次或多次的面试官
            // const stepInterviewerFlag = (() => {
            //     if (resumeStep === 1 || !candidateId || !interviewDetailList.length) {
            //         return false;
            //     }
            //     return isInterviewer(
            //         interviewDetailList.reduce((pre, item) => {
            //             const curr = item?.arrangeDetailVO?.interviewEmployees || [];
            //             return [...pre, ...curr];
            //         }, [])
            //     );
            // })();
            // 推荐/不推荐按钮
            const thumbCommentGroup = (
                <ThumbCommentGroup
                    onChange={() => pushRefreshComponents(['TalentStatusStep'])}
                    initState={{
                        praiseEmployeeNameList,
                        trampleEmployeeNameList,
                        evaluateType
                    }}
                    resumeId={id}
                    record={talentInfo || {}}
                    onRefresh={onRefresh}
                ></ThumbCommentGroup>
            );
            const invite = principalFlag && <InterviewInviteOperate button candidateId={candidateId} resumeId={id} />;
            const weedOut = (principalFlag || launcherFlag) && (
                <div
                    onClick={() => {
                        eventTrack({
                            eventName: 'personnel_management_recruitment_demand_list_detail_resume_detail_out_click',
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: `${data?.dutyName}-${talentInfo.talentName}`
                            }
                        });
                    }}
                >
                    <WeedOutOperate
                        button
                        resumeId={id}
                        candidateId={candidateId}
                        onConfirm={() =>
                            pushRefreshComponents([
                                'TalentDutyInfo',
                                'TalentStatusStep',
                                'CandidateDetail',
                                'InterviewDetailList',
                                'HireDetail'
                            ])
                        }
                    />
                </div>
            );
            // 修改面试 -- 需要 contactId 改动较大，待产品确认再添加
            // const editInterview = (principalFlag || launcherFlag) && (
            //     <div>
            //         <InterviewEditOperate button candidateId={queryCandidateId} contactId={queryContactId} />
            //     </div>
            // );
            const transfer = (
                <div
                    onClick={() => {
                        eventTrack({
                            eventName: 'personnel_management_recruitment_demand_list_detail_resume_detail_relay_click',
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: `${data?.dutyName}-${talentInfo.talentName}`
                            }
                        });
                    }}
                >
                    <TransferOperate button resumeId={id} />
                </div>
            );
            const backgroundRec = <BackgroundRecOperate button candidateId={candidateId} employId={employId} />;
            const recommend = (
                <div
                    onClick={() => {
                        eventTrack({
                            eventName:
                                'personnel_management_recruitment_demand_list_detail_resume_detail_tjdqtgw_click',
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: `${data?.dutyName}-${talentInfo.talentName}`
                            }
                        });
                    }}
                >
                    <RecommendOperate
                        button
                        weedOutDisabled={!(principalFlag || launcherFlag)}
                        resumeId={id}
                        onConfirm={() =>
                            pushRefreshComponents([
                                'TalentStatusStep',
                                'CandidateDetail',
                                'InterviewDetailList',
                                'HireDetail'
                            ])
                        }
                    />
                </div>
            );

            const defaultNoticeEmployee = new Set();
            recruitList.forEach(item => {
                defaultNoticeEmployee.add(item.launchEmployeeCode);
                defaultNoticeEmployee.add(item.principalEmployeeCode);
            });
            // 加入/移出黑名单
            let messageType = 0; // 黑名单提示语类型
            const { resumeLabel } = talentDutyInfo?.dutyList?.find(v => v.resumeId === Number(id)) || {};
            if (![2, 3].includes(resumeLabel)) {
                // 提示类型1：应聘中：【面试】【录用】阶段
                if ([3, 4].includes(resumeStep) && resumeLabel === 1) {
                    messageType = 1;
                }
                // 提示类型2：【简历】【候选】阶段
                if ([1, 2].includes(resumeStep)) messageType = 2;
            }
            const moveToBlack = (
                <TalentsBlackListOperate
                    key={talentDutyInfo?.hasBlackList ? 'remove' : 'add'}
                    talentCode={talentInfo?.talentCode}
                    button
                    operateType={talentDutyInfo?.hasBlackList ? 'remove' : 'add'}
                    onRefresh={() => {
                        pushRefreshComponents([
                            'TalentDutyInfo',
                            'TalentStatusStep',
                            'InterviewDetailList',
                            'HireDetail'
                        ]);
                    }}
                    defaultNoticeEmployee={Array.from(defaultNoticeEmployee)}
                    resumeStep={talentInfo?.resumeStep}
                    messageType={messageType}
                />
            );
            if (talentDutyInfo?.hasBlackList) {
                return [moveToBlack];
            }
            // 简历阶段
            if (resumeStep === 1) {
                return [moveToBlack, transfer, recommend, thumbCommentGroup];
            }
            // 候选阶段
            if (resumeStep === 2) {
                // 1 候选 2 淘汰 3 待接受 5 已取消
                const arr = [
                    [],
                    [moveToBlack, invite, weedOut, transfer, recommend, thumbCommentGroup],
                    [moveToBlack, invite, transfer, recommend, thumbCommentGroup],
                    [moveToBlack, weedOut, transfer, recommend],
                    [],
                    [moveToBlack, invite, weedOut, transfer, recommend, thumbCommentGroup],
                    [],
                    [],
                    [thumbCommentGroup, weedOut, transfer, recommend]
                ];
                return arr[candidateStatus] || [];
            }
            // 面试阶段
            if (resumeStep === 3) {
                // 1 待接受 2 待面试 3 待总结 4 已通过 5 已淘汰 6 需复试 7 已取消
                const arr = [
                    [],
                    [moveToBlack, weedOut, transfer, recommend, thumbCommentGroup],
                    [moveToBlack, weedOut, transfer, recommend, thumbCommentGroup],
                    [moveToBlack, weedOut, transfer, recommend, thumbCommentGroup],
                    [],
                    [moveToBlack, invite, transfer, recommend, thumbCommentGroup],
                    [moveToBlack, invite, weedOut, transfer, recommend, thumbCommentGroup],
                    [moveToBlack, invite, weedOut, transfer, recommend, thumbCommentGroup]
                ];
                return arr[interviewStatus] || [];
            }
            if (resumeStep === 4) {
                // 1=待处理 2=需协商 3=审批中 4=审批拒绝 5=审批撤回 6=待接收  7=已接受 8=已取消 9=已入职 10已淘汰 99=其他）
                if (resumeLabel === 3 && resumeLabel) {
                    return [moveToBlack, transfer, recommend, backgroundRec, thumbCommentGroup];
                }
                if (resumeLabel) {
                    return [moveToBlack, weedOut, transfer, recommend, backgroundRec, thumbCommentGroup];
                }
                return [];
            }
            return [];
        };

        return <Operates operates={fetchOperates()} spaceSplit />;
    };

    /**
     * 渲染面试岗位下拉框
     */
    const renderDuties = useRenderDuty({
        talentDutyInfo,
        resumeId: data.data?.resumeId,
        query,
        loading: talentDutyInfoLoading || loading
    });

    // if (loading) {
    //     return renderSpin();
    // }

    const allLoading = candidateDetailDetailLoading || interviewDetailListLoading || loading;

    return (
        <TalentDetailContext.Provider value={talentInfo}>
            <PageContainer>
                <div style={{ margin: 16 }}>
                    {/* 头部 */}
                    <Row type="flex" justify="space-between" align="top" style={{ marginBottom: 24 }}>
                        <TalentInfoHead talent={talentInfo} dutyCom={renderDuties()} disableRedirect />
                        {renderBtn()}
                    </Row>
                    <Spin spinning={allLoading}>
                        <Row type="flex" style={{ marginTop: '20' }}>
                            <Tabs
                                type="card"
                                className={styles.cardTabs}
                                activeKey={tabActiveKey}
                                onChange={handleTabChange}
                                style={{ flex: 1 }}
                                onTabClick={key => {
                                    const eventMap = {
                                        RESUME:
                                            'personnel_management_recruitment_demand_list_detail_resume_detail_info_click',
                                        INTERVIEW:
                                            'personnel_management_recruitment_demand_list_detail_resume_detail_interview_click',
                                        HIRE:
                                            'personnel_management_recruitment_demand_list_detail_resume_detail_offer_click'
                                    };

                                    eventTrack({
                                        eventName: eventMap[key],
                                        pageName: 'personnel_management_recruitment',
                                        eventProps: {
                                            click_context: `${data?.dutyName}-${talentInfo.talentName}`
                                        }
                                    });
                                }}
                            >
                                {auth.RESUME && (
                                    <Tabs.TabPane tab="简历信息" key="RESUME">
                                        <ResumeDetail />
                                    </Tabs.TabPane>
                                )}
                                {auth.INTERVIEW && interviewTab}
                                {auth.HIRE && hireTab}
                            </Tabs>
                            <div
                                style={{
                                    position: 'relative',
                                    marginTop: 39,
                                    width: stepShow ? 64 : 33,
                                    borderTop: '1px solid rgb(232, 232, 232)'
                                }}
                            >
                                <div
                                    style={{
                                        position: 'absolute',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        zIndex: 1000,
                                        top: 100,
                                        left: 11,
                                        width: 22,
                                        height: 36,
                                        cursor: 'pointer',
                                        background: '#FFFFFF',
                                        boxShadow: '-4px 0px 8px 0px rgba(0, 0, 0, 0.06)',
                                        borderRadius: '4px 0px 0px 4px',
                                        border: '1px solid #EEEEEE',
                                        borderRight: 0
                                    }}
                                    onClick={() => {
                                        eventTrack({
                                            eventName:
                                                'personnel_management_recruitment_demand_list_detail_resume_detail_open_close_click',
                                            pageName: 'personnel_management_recruitment',
                                            eventProps: {
                                                click_context: `${data?.dutyName}-${talentInfo.talentName}`
                                            }
                                        });
                                        setStepShow(val => !val);
                                    }}
                                >
                                    <Icon type={stepShow ? 'right' : 'left'} />
                                </div>
                                <div
                                    style={{
                                        marginLeft: 32,
                                        borderLeft: '1px solid rgb(232, 232, 232)',
                                        width: 0,
                                        height: '100%'
                                    }}
                                ></div>
                            </div>
                            <div
                                style={{
                                    width: stepShow ? 280 : 0,
                                    opacity: stepShow ? 1 : 0,
                                    maxHeight: stepShow ? 99999 : 0,
                                    overflow: stepShow ? 'initial' : 'hidden',
                                    transition: 'all 0.8s ',
                                    flex: 'none',
                                    marginTop: 39,
                                    paddingTop: 20,
                                    borderTop: '1px solid rgb(232, 232, 232)'
                                }}
                                onClick={() => {
                                    eventTrack({
                                        eventName:
                                            'personnel_management_recruitment_demand_list_detail_resume_detail_process_info_click',
                                        pageName: 'personnel_management_recruitment',
                                        eventProps: {
                                            click_context: `${data?.dutyName}-${talentInfo.talentName}`
                                        }
                                    });
                                }}
                            >
                                <TalentStatusStep
                                    talentId={id}
                                    refresh={getRefreshByKey('TalentStatusStep')}
                                    onRefreshed={() => removeRefreshedComponent('TalentStatusStep')}
                                />
                            </div>
                        </Row>
                    </Spin>
                </div>
            </PageContainer>
        </TalentDetailContext.Provider>
    );
};
export default connect(({ user }) => ({ user }))(Detail);
